package top.lywivan.core.registrar;

import com.sun.xml.internal.ws.client.sei.MethodHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AliasFor;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @desc
 * @author:ivan.liu
 */
@Slf4j
@Data
public class MyLywFactoryBean implements FactoryBean<Object> {

    /**
     * 定义Lyw接口的属性
     */
    private String value;

    private String name;

    private String password;

    // 标注了@Lyw注解的接口 Class
    private Class<?> type;


    @Override
    public Object getObject() throws Exception {
        //基于JDK生成代理
        log.debug("已经为接口：{}生成代理对象",type.getName());
        return Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(ReflectionUtils.isObjectMethod(method)){
                    return method.invoke(method.getDeclaringClass().newInstance(),args);
                }
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                log.debug("配置的属性包括：value={}，name={}，password={}",value,name,password);
                log.debug("解析到方法上的接口的参数：{}", Arrays.toString(annotation.value()));
                return "调用成功！";
            }
        });
    }

    @Override
    public Class<?> getObjectType() {
        return this.type;
    }
}
